# -*- coding:utf-8 -*-
import requests
import datetime
import json
from requests.exceptions import BaseHTTPError
from ElevatorAdmin import settings
from users.models import Registry, CompanyWebsiteInfo, Person, AuthUser
from basic.models import ElevatorInfo, ElevatorPersonInfo
from utils.logger import get_logger
from maintenance.models import Contract, Task
import users.views
from django.db.models.signals import post_save
import time
from response import ErrorCode
# from ElevatorAdmin.tasks import test_for_celery
from celery import shared_task


logger = get_logger(__name__)


def elevator_admin_info(url, **kwargs):
    headers = {'Content-Type': 'application/json'}
    try:
        res = requests.post(url, headers=headers, data=kwargs)
    except BaseHTTPError as e:
        status = False
        message = 'Error Occurred:(reason)'.format(reason=str(e.args))
        return status, message
    status = True
    data = res.json()
    return status, data


def set_status(reg_obj, status):
    post_save.disconnect(receiver=users.views.company_registry, sender=reg_obj.__class__)
    end_time = datetime.datetime.now()
    if status:
        reg_obj.registry_status = 20
    else:
        reg_obj.registry_status = 30
    reg_obj.registry_time = end_time
    reg_obj.save()
    post_save.connect(receiver=users.views.company_registry, sender=reg_obj.__class__)


def set_binded(reg_obj, status):
    post_save.disconnect(receiver=users.views.company_registry, sender=reg_obj.__class__)
    end_time = datetime.datetime.now()
    if status:
        reg_obj.is_binded = 20
    else:
        reg_obj.is_binded = 30
    reg_obj.registry_time = end_time
    reg_obj.save()
    post_save.connect(receiver=users.views.company_registry, sender=reg_obj.__class__)


def get_contract_data(contract_obj, elevator_obj):
    contract_info = dict()
    contract_info["contract_no"] = contract_obj.contract_no
    contract_info["contract_name"] = contract_obj.contract_name
    contract_info["dev_name"] = elevator_obj.elevator_name
    contract_info["dev_code"] = elevator_obj.register_code
    contract_info["user_company"] = contract_obj.property_company.name
    if contract_obj.maintain_cycle == 10:
        contract_info["maintenance_cycle"] = 15
        # contract_info['maintenance_cycle'] = '半月保'
    elif contract_obj.maintain_cycle == 20:
        contract_info["maintenance_cycle"] = 30
        # contract_info['maintenance_cycle'] = '月保'
    elif contract_obj.maintain_cycle == 30:
        contract_info["maintenance_cycle"] = 90
        # contract_info['maintenance_cycle'] = '季保'
    elif contract_obj.maintain_cycle == 40:
        contract_info["maintenance_cycle"] = 365
        # contract_info['maintenance_cycle'] = '年保'
    contract_info["start_time"] = contract_obj.start_time
    contract_info["end_time"] = contract_obj.end_time
    contract_files = json.loads(contract_obj.contract_file)
    contract_info["file"] = ",".join(contract_files)
    if elevator_obj.elevator_property == 10:
        contract_info["dev_property"] = "安置房小区"
    elif elevator_obj.elevator_property == 20:
        contract_info["dev_property"] = "商品房小区"
    elif elevator_obj.elevator_property == 30:
        contract_info["dev_property"] = "医院、学校、机关事业单位"
    elif elevator_obj.elevator_property == 40:
        contract_info["dev_property"] = "其他"
    return contract_info


def registry_contract_elevator(elevator_qs, type_for_reg, reg_obj_id, start_time):
    try:
        company_obj = type_for_reg.objects.get(id=reg_obj_id).maintain_company
        contract_obj = Contract.objects.get(id=reg_obj_id)
    except Exception as e:
        return
    link_account = company_obj.link_account
    link_token = company_obj.link_token
    lis = list()
    lis_2 = list()
    lis_1 = list()
    reg_dic = dict()
    commit_num = True

    for elevator_obj in elevator_qs:
        try:
            contract_info = get_contract_data(contract_obj, elevator_obj)
            lis_2.append(contract_info)
        except Exception as e:
            print e
    res = update_wb_contract_info(link_account, link_token, lis_2)
    if u'请勿重复提交' in res['Message']:
        print u'重复提交'
        for elevator_obj in elevator_qs:
            primary_key = elevator_obj.register_code
            primary_type = "维保合同"
            if elevator_obj.registry_status == 20:
                elevator_info = get_contract_data(contract_obj, elevator_obj)
                elevator_info = {
                    "UserCompanyName": elevator_info['user_company'],
                    "DevCode": elevator_info['dev_code']
                }
                lis_1.append(elevator_info)
                continue
            else:
                time.sleep(0.5)
                pass_info = query_maintainance_confirm_info(link_account, link_token, primary_key, primary_type)
                if pass_info['Code'] == 200:
                    if pass_info['Status']:
                        set_status(reg_obj=elevator_obj, status=True)
                    elif not pass_info['Status'] and u'出现错误' in pass_info['Message']:
                        status = False
                        msg = u'备案服务器异常，请稍后再试'
                        data = res['Data']
                        ret_info = res['ret_info']
                        reg_info = res['reg_info']
                        end_time = datetime.datetime.now()
                        reg_dic['type_for_reg'] = type_for_reg.__name__
                        reg_dic['reg_obj_id'] = reg_obj_id
                        reg_dic['start_time'] = start_time
                        reg_dic['end_time'] = end_time
                        reg_dic['status'] = status
                        reg_dic['msg'] = msg
                        reg_dic['data'] = data
                        reg_dic['reg_info'] = json.dumps(reg_info)
                        reg_dic['ret_info'] = ret_info
                        return reg_dic
                    elif not pass_info['Status'] and u'信息不存在，请上传后再试' in pass_info['Message']:
                        commit_num = False
                        try:
                            contract_info = get_contract_data(contract_obj, elevator_obj)
                            lis.append(contract_info)
                        except Exception as e:
                            print e
                else:
                    status = False
                    msg = u'备案服务器异常，请稍后再试'
                    data = res['Data']
                    ret_info = res['ret_info']
                    reg_info = res['reg_info']
                    end_time = datetime.datetime.now()
                    reg_dic['type_for_reg'] = type_for_reg.__name__
                    reg_dic['reg_obj_id'] = reg_obj_id
                    reg_dic['start_time'] = start_time
                    reg_dic['end_time'] = end_time
                    reg_dic['status'] = status
                    reg_dic['msg'] = msg
                    reg_dic['data'] = data
                    reg_dic['reg_info'] = json.dumps(reg_info)
                    reg_dic['ret_info'] = ret_info
                    return reg_dic
        if not commit_num:
            res = update_wb_contract_info(link_account, link_token, lis)
            status = res['Status']
            msg = res['Message']
            data = res['Data']

            reg_info = res["reg_info"]
            reg_info = json.loads(reg_info)
            if lis_1:
                for item in lis_1:
                    logger.info('item')
                    logger.info(item)
                    reg_info["Content"].append(item)
            reg_info = json.dumps(reg_info)

            ret_info = res['ret_info']
            end_time = datetime.datetime.now()

            reg_dic['type_for_reg'] = type_for_reg.__name__
            reg_dic['reg_obj_id'] = reg_obj_id
            reg_dic['start_time'] = start_time
            reg_dic['end_time'] = end_time
            reg_dic['status'] = status
            reg_dic['msg'] = msg
            reg_dic['data'] = data
            reg_dic['reg_info'] = reg_info
            reg_dic['ret_info'] = ret_info
            return reg_dic
        else:
            for elevator_obj in elevator_qs:
                set_status(reg_obj=elevator_obj, status=True)
                try:
                    contract_info = get_contract_data(contract_obj, elevator_obj)
                    lis.append(contract_info)
                except Exception as e:
                    print e
            commit_data = {
                "account": link_account,
                "token": link_token,
                "Content": [
                ]
            }

            for item in lis:
                dic = {
                    "ContractNo": item["contract_no"],
                    "ContractName": item["contract_name"],
                    "DevName": item["dev_name"],
                    "DevCode": item["dev_code"],
                    "MaintenanceCycle": item["maintenance_cycle"],
                    "StartTime": item["start_time"],
                    "EndTime": item["end_time"],
                    "File": item["file"],
                    "DevProperty": item["dev_property"],
                    "UserCompanyName": item["user_company"]
                }
                commit_data["Content"].append(dic)
            status = True
            msg = u"提交成功"
            data = None
            reg_info = json.dumps(commit_data)
            ret_info = {
                "Status": True,
                "Message": u"提交成功",
                "Data": None
            }
            ret_info = json.dumps(ret_info)
            end_time = datetime.datetime.now()

            reg_dic['type_for_reg'] = type_for_reg.__name__
            reg_dic['reg_obj_id'] = reg_obj_id
            reg_dic['start_time'] = start_time
            reg_dic['end_time'] = end_time
            reg_dic['status'] = status
            reg_dic['msg'] = msg
            reg_dic['data'] = data
            reg_dic['reg_info'] = reg_info
            reg_dic['ret_info'] = ret_info
            return reg_dic
    else:
        status = res['Status']
        msg = res['Message']
        data = res['Data']
        reg_info = res["reg_info"]
        ret_info = res['ret_info']
        end_time = datetime.datetime.now()

        reg_dic['type_for_reg'] = type_for_reg.__name__
        reg_dic['reg_obj_id'] = reg_obj_id
        reg_dic['start_time'] = start_time
        reg_dic['end_time'] = end_time
        reg_dic['status'] = status
        reg_dic['msg'] = msg
        reg_dic['data'] = data
        reg_dic['reg_info'] = reg_info
        reg_dic['ret_info'] = ret_info
        return reg_dic


def registry_wb_company_info(type_for_reg, reg_obj_id):
    print '公司备案开始'
    start_time = datetime.datetime.now()
    try:
        reg_obj = type_for_reg.objects.get(id=reg_obj_id)
    except Exception as e:
        print e
        return
    website_obj = CompanyWebsiteInfo.objects.get(company=reg_obj_id)
    # 维保公司信息
    link_account = reg_obj.link_account
    link_token = reg_obj.link_token
    company_name = reg_obj.name
    unified_code = reg_obj.unified_code
    register_area_code = reg_obj.register_street
    register_address = reg_obj.register_address
    legal_person = reg_obj.legal_person
    legal_phone = reg_obj.legal_phone
    main_person = reg_obj.person_in_charge
    main_person_phone = reg_obj.person_in_charge_phone
    business_license = reg_obj.business_lic
    special_license = reg_obj.lic_pic
    # 维保网点信息
    office_address = website_obj.office_address
    province_code = website_obj.province_code
    city_code = website_obj.city_code
    county_code = website_obj.county_code
    street_code = website_obj.street_code
    emergency_phone = website_obj.emergency_phone
    office_main_person = website_obj.office_main_person
    office_main_person_phone = website_obj.office_main_person_phone
    res = update_wb_company_info(link_account, link_token, company_name, unified_code, register_area_code,
                                 register_address, legal_person, legal_phone, main_person, main_person_phone,
                                 business_license, special_license, office_address, province_code, city_code,
                                 county_code, street_code, emergency_phone, office_main_person,
                                 office_main_person_phone)
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    Registry.objects.create(type_for_reg=type_for_reg.__name__, reg_obj_id=reg_obj_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info, ret_info=ret_info)
    # if status:
    #     reg_obj.registry_status = 20
    # else:
    #     reg_obj.registry_status = 30
    # reg_obj.registry_time = end_time
    # reg_obj.save()
    set_status(reg_obj=reg_obj, status=status)
    print '备案完毕'


def update_wb_company_info(link_account, link_token, company_name, unified_code, register_area_code, register_address, legal_person, legal_phone,
                           main_person, main_person_phone, business_license, special_license, office_address,
                           province_code, city_code, county_code, street_code, emergency_phone, office_main_person,
                           office_main_person_phone):
    """

    企业名称: company_name
    信用代码: unified_code
    注册街道代码: register_area_code
    注册地址: register_address
    法人: legal_person
    法人手机: legal_phone
    主要负责人: main_person
    主要负责人手机: main_person_phone
    营业执照: business_license
    特种设备许可证: special_license
    维保网点地址: office_address
    维保网点省份区域代码: province_code
    维保网点所在城市区域代码: city_code
    维保网点所在县乡镇区域代码: county_code
    维保网点所在街道区域代码: street_code
    24小时电话: emergency_phone
    维保网点负责人: office_main_person
    维保网点负责人电话: office_main_person_phone
    """
    # headers = {'Content-Type': 'application/json'}
    data = {
        'account': link_account,
        'token': link_token,
        'Content': {
            'CompanyName': company_name,
            'UnifiedCode': unified_code,
            'RegisterArea': register_area_code,
            'RegisterAddr': register_address,
            'LegalPerson': legal_person,
            'LegalPhone': legal_phone,
            'MainPerson': main_person,
            'MainPPhone': main_person_phone,
            'BusinessLic': business_license,
            'LicPic': special_license,
            'OfficeAddr': office_address,
            'WBProvinceCode': province_code,
            'WBCityCode': city_code,
            'WBCountyCode': county_code,
            'WBStreetCode': street_code,
            'AllDayPhone': emergency_phone,
            'OfficeMainPerson': office_main_person,
            'OfficeMainPhone': office_main_person_phone
        }

    }
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['COMPANY'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def registry_wb_person_info(type_for_reg, reg_obj_id):
    print '维保人员备案开始'
    start_time = datetime.datetime.now()
    try:
        person_obj = type_for_reg.objects.get(id=reg_obj_id)
    except Exception as e:
        print e
        return
    company_obj = person_obj.company
    auth_obj = person_obj.auth_user
    link_account = company_obj.link_account
    link_token = company_obj.link_token
    lis = list()
    person_info = dict()
    person_info['real_name'] = auth_obj.real_name
    person_info['phone'] = auth_obj.phone
    person_info['card_id'] = person_obj.card_id
    person_info['t1_card_no'] = person_obj.t1_card_no if person_obj.t1_card_no else ''
    person_info['t1_card_file'] = person_obj.t1_card_file if person_obj.t1_card_file else ''
    # t1_time = person_obj.t1_end_time.split('-')
    # t1_time = '/'.join(t1_time)
    person_info['t1_end_time'] = person_obj.t1_end_time if person_obj.t1_end_time else ''
    person_info['t2_card_no'] = person_obj.t2_card_no if person_obj.t2_card_no else ''
    person_info['t2_card_file'] = person_obj.t2_card_file if person_obj.t2_card_file else ''
    # t2_time = person_obj.t2_end_time.split('-')
    # t2_time = '/'.join(t2_time)
    person_info['t2_end_time'] = person_obj.t2_end_time if person_obj.t2_end_time else ''
    person_info['user_status'] = '在职' if person_obj.status == 10 else '离职'

    # contract_start_time = person_obj.contract_start_time.split('-')
    # contract_start_time = '/'.join(contract_start_time)
    person_info['contract_start_time'] = person_obj.contract_start_time
    # contract_end_time = person_obj.contract_end_time.split('-')
    # contract_end_time = '/'.join(contract_end_time)
    person_info['contract_end_time'] = person_obj.contract_end_time
    contract_files = person_obj.contract_file
    if contract_files:
        contract_files = json.loads(contract_files)
        contract_files = ','.join(contract_files)
    person_info['contract_file'] = contract_files
    person_info['social_card_file'] = person_obj.social_security
    lis.append(person_info)
    res = register_wb_person(link_account, link_token, lis)
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    Registry.objects.create(type_for_reg=type_for_reg.__name__, reg_obj_id=reg_obj_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info, ret_info=ret_info)
    # if status:
    #     person_obj.registry_status = 20
    # else:
    #     person_obj.registry_status = 30
    # person_obj.registry_time = end_time
    # person_obj.save()
    set_status(reg_obj=person_obj, status=status)
    print '备案完毕'


def register_wb_person(link_account, link_token, lis):
    """

    姓名: real_name
    手机号: phone
    身份证: card_id
    T1证号: t1_card_no
    T1证附件: t1_card_file
    T1证有效期: t1_end_time
    T2证号: t2_card_no
    T2证附件: t2_card_file
    T2证有效期: t2_end_time
    状态: user_status
    劳动合同开始日期: contract_start_time
    劳动合同结束日期: contract_end_time
    劳动合同附件: contract_file
    社保证明附件: social_card_file
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': [
        ]
    }
    for item in lis:
        dic = {
            'UserName': item['real_name'],
            'Phone': item['phone'],
            'CardId': item['card_id'],
            'T1CardNo': item['t1_card_no'],
            'T1CardFile': item['t1_card_file'],
            'T1EndTime': item['t1_end_time'],
            'T2CardNo': item['t2_card_no'],
            'T2CardFile': item['t2_card_file'],
            'T2EndTime': item['t2_end_time'],
            'UserStatus': item['user_status'],
            'ContractStartTime': item['contract_start_time'],
            'ContractEndTime': item['contract_end_time'],
            'ContractFile': item['contract_file'],
            'SocialCardFile': item['social_card_file']
        }
        data['Content'].append(dic)
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['PERSONNEL'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        ret = res.json()
        ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def registry_wb_contract_info(type_for_reg, reg_obj_id):
    print '合同备案开始'
    start_time = datetime.datetime.now()
    try:
        company_obj = type_for_reg.objects.get(id=reg_obj_id).maintain_company
        contract_obj = Contract.objects.get(id=reg_obj_id)
    except Exception as e:
        return
    link_account = company_obj.link_account
    link_token = company_obj.link_token
    elevator_qs = ElevatorInfo.objects.filter_active(contract=reg_obj_id)
    elevator_nums = elevator_qs.count()
    if 0 < elevator_nums <= 50:
        reg_dic = registry_contract_elevator(elevator_qs, type_for_reg, reg_obj_id, start_time)
        logger.info(u'合同备案开始...........数量不到50')
        Registry.objects.create(type_for_reg=reg_dic['type_for_reg'], reg_obj_id=reg_dic['reg_obj_id'],
                                start_time=reg_dic['start_time'], end_time=reg_dic['end_time'],
                                status=reg_dic['status'], msg=reg_dic['msg'], data=reg_dic['data'],
                                reg_info=reg_dic['reg_info'], ret_info=reg_dic['ret_info'])
        set_status(reg_obj=contract_obj, status=reg_dic['status'])
        if reg_dic['status']:
            for elevator_obj in elevator_qs:
                set_status(reg_obj=elevator_obj, status=True)
                registry_bind_lift_person_info(ElevatorInfo, elevator_obj.id)
        else:
            for elevator_obj in elevator_qs:
                if elevator_obj.registry_status != 20:
                    set_status(reg_obj=elevator_obj, status=False)
    elif elevator_nums > 50:
        print '合同备案开始...........数量大于50'
        info_lis = list()
        n = elevator_nums // 50

        for i in range(1, n+2):
            length = i * 50
            elevator_qs_l = list(ElevatorInfo.objects.filter_active(contract=reg_obj_id))[length-50:length]
            reg_dic = registry_contract_elevator(elevator_qs_l, type_for_reg, reg_obj_id, start_time)
            if not reg_dic['status']:
                for elevator_obj in elevator_qs_l:
                    if elevator_obj.registry_status != 20:
                        set_status(reg_obj=elevator_obj, status=False)
            else:
                for elevator_obj in elevator_qs_l:
                    registry_bind_lift_person_info(ElevatorInfo, elevator_obj.id)
                    set_status(reg_obj=elevator_obj, status=True)
            info_lis.append(reg_dic)

        contract_commit = True
        reg_info_g = {
            'account': link_account,
            'token': link_token,
            'Content': [
            ]
        }

        for reg_dic in info_lis:
            for item in json.loads(reg_dic['reg_info'])['Content']:
                reg_info_g['Content'].append(item)

        for reg_dic in info_lis:
            if not reg_dic['status']:
                contract_commit = False
                Registry.objects.create(type_for_reg=reg_dic['type_for_reg'], reg_obj_id=reg_dic['reg_obj_id'],
                                        start_time=reg_dic['start_time'], end_time=reg_dic['end_time'],
                                        status=reg_dic['status'], msg=reg_dic['msg'], data=reg_dic['data'],
                                        reg_info=json.dumps(reg_info_g), ret_info=reg_dic['ret_info'])
                set_status(reg_obj=contract_obj, status=reg_dic['status'])
                break

        if contract_commit:
            reg_info_g = {
                'account': link_account,
                'token': link_token,
                'Content': [
                ]
            }

            for reg_dic in info_lis:
                for item in json.loads(reg_dic['reg_info'])['Content']:
                    reg_info_g['Content'].append(item)

            reg_dic = info_lis[-1]
            Registry.objects.create(type_for_reg=reg_dic['type_for_reg'], reg_obj_id=reg_dic['reg_obj_id'],
                                    start_time=reg_dic['start_time'], end_time=reg_dic['end_time'],
                                    status=reg_dic['status'], msg=reg_dic['msg'], data=reg_dic['data'],
                                    reg_info=json.dumps(reg_info_g), ret_info=reg_dic['ret_info'])
            set_status(reg_obj=contract_obj, status=reg_dic['status'])
    else:
        print '合同备案开始...........数量不清楚'
        commit_data = {
            "account": link_account,
            "token": link_token,
            "Content": [
            ]
        }
        status = False
        msg = u"导入合同列表为空"
        data = None
        reg_info = json.dumps(commit_data)
        ret_info = {
            "Status": False,
            "Message": u"导入合同列表为空",
            "Data": None
        }
        end_time = datetime.datetime.now()
        Registry.objects.create(type_for_reg=type_for_reg.__name__, reg_obj_id=reg_obj_id, start_time=start_time,
                                end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                                ret_info=json.dumps(ret_info))
        set_status(reg_obj=contract_obj, status=False)
    print '备案完毕'


def update_wb_contract_info(link_account, link_token, lis):
    """
    合同编号: contract_no
    合同名称: contract_name
    设备简称: dev_name
    设备代码: dev_code
    维保周期: maintenance_cycle
    合同开始时间: start_time
    合同结束时间: end_time
    合同附件: file
    设备性质: dev_property
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': [
        ]
    }
    for item in lis:
        dic = {
            'ContractNo': item['contract_no'],
            'ContractName': item['contract_name'],
            'DevName': item['dev_name'],
            'DevCode': item['dev_code'],
            'MaintenanceCycle': item['maintenance_cycle'],
            'StartTime': item['start_time'],
            'EndTime': item['end_time'],
            'File': item['file'],
            'DevProperty': item['dev_property'],
            'UserCompanyName': item['user_company']
        }
        data['Content'].append(dic)
    # logger.info('data-Content')
    # logger.info(data)
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['CONTRACT'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def query_maintainance_confirm_info(link_account, link_token, primary_key, primary_type):
    """

    查询主键: primary_key
    查询主键涉及事项: primary_type
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': {
            'PrimaryKey': primary_key,
            'PrimaryType': primary_type,
        }
    }
    res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['QUERY'], json=data)
    if res.status_code == 200:
        # if res:
        ret = res.json()
        ret.update({"Code": res.status_code})
        # else:
        #     res = {
        #             "Status": False,
        #             "Message": u"备案服务器异常",
        #             "Data": None
        #         }
        #     ret = res
        #     ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "Code":res.status_code}
    return ret


def get_elevator_person_info(elevator_person_qs, elevator_obj):
    lis = list()
    for elevator_person_obj in elevator_person_qs:
        elevator_person_info = dict()
        elevator_person_info['dev_code'] = elevator_obj.register_code
        if elevator_person_obj.worker.t1_card_no:
            elevator_person_info['certificate_id'] = elevator_person_obj.worker.t1_card_no
        elif elevator_person_obj.worker.t2_card_no:
            elevator_person_info['certificate_id'] = elevator_person_obj.worker.t2_card_no
        else:
            elevator_person_info['certificate_id'] = None

        if elevator_person_obj.worker_type == 10:
            elevator_person_info['user_type'] = u'维保人员'
        elif elevator_person_obj.worker_type == 20:
            elevator_person_info['user_type'] = u'救援人员'
        elif elevator_person_obj.worker_type == 30:
            elevator_person_info['user_type'] = u'急修人员'
        else:
            elevator_person_info['user_type'] = u'其他'
        if elevator_person_obj.status == 10:
            elevator_person_info['operation_type'] = u'绑定'
        elif elevator_person_obj.status == 20:
            elevator_person_info['operation_type'] = u'解绑'
        lis.append(elevator_person_info)
    return lis


def registry_bind_lift_person_info(type_for_reg, reg_obj_id):
    print '电梯备案开始 %s' % reg_obj_id
    start_time = datetime.datetime.now()
    elevator_obj = type_for_reg.objects.get(id=reg_obj_id)
    company_obj = elevator_obj.maintain_company
    link_account = company_obj.link_account
    link_token = company_obj.link_token
    task_qs = Task.objects.filter_active(elevator=reg_obj_id, status=10)
    if elevator_obj.is_active:
        try:
            elevator_person_qs = ElevatorPersonInfo.objects.filter(elevator=reg_obj_id)
        except Exception as e:
            return
        if elevator_person_qs.count() > 0:
            lis = get_elevator_person_info(elevator_person_qs, elevator_obj)
            res = bind_lift_person_info(link_account, link_token, lis)
            status = res['Status']
            msg = res['Message']
            data = res['Data']
            reg_info = res['reg_info']
            ret_info = res['ret_info']
            end_time = datetime.datetime.now()
            Registry.objects.create(type_for_reg=type_for_reg.__name__, reg_obj_id=reg_obj_id, start_time=start_time,
                                    end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                                    ret_info=ret_info)
            set_binded(elevator_obj, status)
            if status:  # 提交更新成功
                relieve_person_ids = []
                bind_person_ids = []
                for elevator_person_obj in elevator_person_qs:
                    if elevator_person_obj.status == 20:
                        if elevator_person_obj.worker_type == 10:
                            relieve_person_ids.append(elevator_person_obj.worker.id)
                        elevator_person_obj.delete()  # 删除电梯人员绑定关系
                    elif elevator_person_obj.is_new:
                        if elevator_person_obj.worker_type == 10:
                            bind_person_ids.append(elevator_person_obj.worker.id)
                        elevator_person_obj.is_new = False
                        elevator_person_obj.save()
                if task_qs.count():
                    for task_obj in task_qs:
                        worker_ids = json.loads(task_obj.worker)
                        # 存在解绑人员的情况
                        if relieve_person_ids:
                            for person_id in relieve_person_ids:
                                if person_id in worker_ids:
                                    worker_ids.remove(person_id)
                                else:
                                    continue
                            task_obj.worker = json.dumps(worker_ids)
                            task_obj.save()

                        else:
                            pass

                        # 存在增加人员绑定的情况
                        if bind_person_ids:
                            for person_id in bind_person_ids:
                                if person_id not in worker_ids:
                                    worker_ids.append(person_id)
                                else:
                                    continue
                            task_obj.worker = json.dumps(worker_ids)
                            task_obj.save()
                        else:
                            pass
                else:
                    pass
            else:  # 提交更新失败  恢复到之前的状态
                for elevator_person_obj in elevator_person_qs:
                    if elevator_person_obj.status == 20:
                        elevator_person_obj.status = 10
                        elevator_person_obj.save()
                    elif elevator_person_obj.is_new:
                        elevator_person_obj.delete()
            # set_binded(elevator_obj, status)
        else:
            pass
    else:
        elevator_person_qs = ElevatorPersonInfo.objects.filter(elevator=reg_obj_id)
        lis = get_elevator_person_info(elevator_person_qs, elevator_obj)
        for item in lis:
            item['operation_type'] = u'解绑'
        res = bind_lift_person_info(link_account, link_token, lis)
        status = res['Status']
        msg = res['Message']
        data = res['Data']
        reg_info = res['reg_info']
        ret_info = res['ret_info']
        end_time = datetime.datetime.now()
        Registry.objects.create(type_for_reg=type_for_reg.__name__, reg_obj_id=reg_obj_id, start_time=start_time,
                                end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                                ret_info=ret_info)
        set_binded(elevator_obj, status)
        ElevatorPersonInfo.objects.filter(elevator=reg_obj_id).delete()
    print '备案完毕'


def bind_lift_person_info(link_account, link_token, lis):
    """

    设备代码: dev_code
    操作证号: certificate_id
    人员类型: user_type
    操作类型: operation_type
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': [
        ]
    }
    for item in lis:
        dic = {
            'DevCode': item['dev_code'],
            'CertificateId': item['certificate_id'],
            'UserType': item['user_type'],
            'Optype': item['operation_type'],
        }
        data['Content'].append(dic)
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['BIND'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def new_wb_mission(link_account, link_token, lis):
    """

    电梯设备代码: dev_code
    首次维保任务截止日期: end_time
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': [
        ]
    }
    for item in lis:
        dic = {
            'DevCode': item['dev_code'],
            'EndTime': item['end_time'],
        }
        data['Content'].append(dic)
    print data
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['NEW_MISSION'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def get_wb_mission(link_account, link_token, dev_code, card_no_list):
    """

    电梯设备代码: dev_code
    操作证编号: card_no_list
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': {
            'DevCode': dev_code,
            'CardNoList': card_no_list,
        }
    }
    logger.info(data)
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['GET_MISSION'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def begin_wb_info(link_account, link_token, task_sheet_id):
    """

    任务单id: task_sheet_id
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': {
            'RwdId': task_sheet_id,
        }
    }
    print data
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['BEGIN_MAINTAIN'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def end_wb_info(link_account, link_token, task_sheet_id, operate_type, card_id, sign_picture, report, items,
                media_type, lic, pic):
    """

    任务单id: task_sheet_id
    作业类型: operate_type
    实际维保人员操作证ID: card_id
    维保签名: sign_picture
    维保报告: report
    需物业配合事项: items
    媒体类型: media_type
    维保检查项: check_item
    检查内容: check_content
    检查结果: check_result
    资料名称: material_name
    资料地址: material_url
    拍照部位名称: part_name
    """
    data = {
        'account': link_account,
        'token': link_token,
        'RwdId': task_sheet_id,
        'OpeateType': operate_type,
        'CardId': card_id,
        'SignPic': sign_picture,
        'Report': report,
        'Items': items,
        'MdeiaType': media_type,
        'Content': {
            'WbItems': [
                # {
                #     'CkItem': check_item,
                #     'CkContent': check_content,
                #     'Ckresult': check_result,
                # }
            ],
            # 'Records': [
                # {
                #     'MaterialName': material_name,
                #     'MaterialUrl': material_url,
                #     'Partname': part_name,
                # }
            # ]
            'Records': pic
        }
    }
    for item in lic:
        wb_item = {'CkItem': item['ckitem'], 'CkContent': item['ckcontent'], 'Ckresult': item['ckvalue']}
        data['Content']['WbItems'].append(wb_item)
    logger.info(data)
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['END_MAINTAIN'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def estate_confirm_info(link_account, link_token, task_sheet_id, estate_sign_url, assessment):
    """

    任务单id: task_sheet_id
    物业签名: estate_sign_url
    物业评价: assessment
    """
    data = {
        'account': link_account,
        'token': link_token,
        'Content': {
            'RwdId': task_sheet_id,
            'DevUserSignUrl': estate_sign_url,
            'Assessment': assessment,
        }
    }
    print data
    try:
        res = requests.post(settings.OFFICIAL_INFO['INTERFACE']['CONFIRM'], json=data)
    except Exception as e:
        logger.info(e)
        ret_info = u"备案接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret

    if res.status_code == 200:
        if res:
            ret = res.json()
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
        else:
            res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
            ret = res
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(ret)})
    else:
        ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
    return ret


def first_maintain_registry(link_account, link_token, task_id, person):

    start_time = datetime.datetime.now()
    task = Task.objects.get(id=task_id)
    elevator = task.elevator
    task_first = Task.objects.filter_active(elevator=elevator, first_maintain_status=20)
    # task_register = Task.objects.filter_active(elevator=elevator, is_first=True).first()
    contract = task.elevator.contract
    flag = False
    if contract and contract.registry_time:
        registry_time = contract.registry_time.date()
        task_new_first = Task.objects.filter_active(elevator=elevator, first_maintain_status=20, day__gte=registry_time)
        if not task_new_first:
            flag = True
    if not task_first or flag:
        dic = {
             'dev_code': task.elevator.register_code,
             'end_time': str(task.day),
        }
        res = new_wb_mission(link_account=link_account, link_token=link_token, lis=[dic])
        status = res['Status']
        msg = res['Message']
        data = res['Data']
        reg_info = res['reg_info']
        ret_info = res['ret_info']
        end_time = datetime.datetime.now()
        Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                                end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                                ret_info=ret_info, task_type=20)
        if not status:
            print task_id, msg, u'首次维保'
            task.status = 110
            task.save()
            return ErrorCode.FIRST_MAINTAIN_REGISTER_FAIL
        task.first_maintain_status = 20
        task.is_first = True
        task.flag = True
        task.first_maintain_time = datetime.datetime.now()
        task.save()
        time.sleep(120)
        # TODO 首次维保后 延时执行查询
    #     return ErrorCode.FIRST_MAINTAIN_REGISTER_COMPLETE
    # if task.first_maintain_time and task.first_maintain_time + datetime.timedelta(seconds=20) > datetime.datetime.now():
    #     return ErrorCode.FIRST_MAINTAIN_REGISTER_COMPLETE

    # workers = task.worker
    # workers = json.loads(workers)
    # persons = Person.objects.filter_active(id__in=workers)
    card_no_list = []
    # for person in persons:
    #     if person.t1_card_no:
    #         card_no_list.append(person.t1_card_no)
    #     if person.t2_card_no:
    #         card_no_list.append(person.t2_card_no)
    # card_no_list = ','.join(card_no_list)
    card_no_list = person.t1_card_no if person.t1_card_no else person.t2_card_no
    res = get_wb_mission(link_account=link_account, link_token=link_token, dev_code=task.elevator.register_code,
                         card_no_list=card_no_list)
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    logger.info(res)
    logger.info("data: %s" % data)
    logger.info("res: %s " % res)
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=30)
    if not status:
        print task_id, msg, u'维保匹配'
        task.status = 120
        task.save()
        return ErrorCode.TASK_MATCH_REGISTER_FAIL
    logger.info(task.id)
    logger.info("task.rwd_id")
    logger.info(data[0]['RwdId'])
    logger.info(type(data[0]['RwdId']))
    # task.rwd_id = data[0]['RwdId']
    rwd_id = data[0]['RwdId']
    print "rwd_id: %s " % rwd_id
    # tasks = Task.objects.filter_active(id=task_id)
    # tasks.update(rwd_id=rwd_id)
    task.rwd_id = rwd_id
    task.save()
    logger.info(task.id)
    logger.info(task.rwd_id)
    res = begin_wb_info(link_account=link_account, link_token=link_token, task_sheet_id=data[0]['RwdId'])
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    logger.info(task.id)
    logger.info(u'最后了')
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=40)
    if not status:
        print task_id, msg, u'维保开始'
        task.status = 130
        task.save()
        # print task_id, msg
        return ErrorCode.TASK_BEGIN_REGISTER_FAIL

    return ErrorCode.SUCCESS


def first_maintain_registry_V2(link_account, link_token, task_id, person):

    start_time = datetime.datetime.now()
    task = Task.objects.get(id=task_id)
    elevator = task.elevator
    task_first = Task.objects.filter_active(elevator=elevator, first_maintain_status=20)
    # task_register = Task.objects.filter_active(elevator=elevator, is_first=True).first()
    contract = task.elevator.contract
    flag = False
    if contract and contract.registry_time:
        registry_time = contract.registry_time.date()
        task_new_first = Task.objects.filter_active(elevator=elevator, first_maintain_status=20, day__gte=registry_time)
        if not task_new_first:
            flag = True
    if not task_first or flag:
        dic = {
             'dev_code': task.elevator.register_code,
             'end_time': str(task.day),
        }
        res = new_wb_mission(link_account=link_account, link_token=link_token, lis=[dic])
        status = res['Status']
        msg = res['Message']
        data = res['Data']
        reg_info = res['reg_info']
        ret_info = res['ret_info']
        end_time = datetime.datetime.now()
        Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                                end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                                ret_info=ret_info, task_type=20)
        if not status:
            print task_id, msg, u'首次维保'
            return ErrorCode.FIRST_MAINTAIN_REGISTER_FAIL
        task.first_maintain_status = 20
        task.is_first = True
        task.flag = True
        task.first_maintain_time = datetime.datetime.now()
        task.save()
        # time.sleep(120)
        # TODO 首次维保后 延时执行查询
        return ErrorCode.FIRST_MAINTAIN_REGISTER_COMPLETE
    if task.first_maintain_time and task.first_maintain_time + datetime.timedelta(seconds=20) > datetime.datetime.now():
        return ErrorCode.FIRST_MAINTAIN_REGISTER_COMPLETE

    # workers = task.worker
    # workers = json.loads(workers)
    # persons = Person.objects.filter_active(id__in=workers)
    card_no_list = []
    # for person in persons:
    #     if person.t1_card_no:
    #         card_no_list.append(person.t1_card_no)
    #     if person.t2_card_no:
    #         card_no_list.append(person.t2_card_no)
    # card_no_list = ','.join(card_no_list)
    card_no_list = person.t1_card_no if person.t1_card_no else person.t2_card_no
    res = get_wb_mission(link_account=link_account, link_token=link_token, dev_code=task.elevator.register_code,
                         card_no_list=card_no_list)
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    logger.info(res)
    logger.info("data: %s" % data)
    logger.info("res: %s " % res)
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=30)
    if not status:
        print task_id, msg, u'维保匹配'
        return ErrorCode.TASK_MATCH_REGISTER_FAIL
    logger.info(task.id)
    logger.info("task.rwd_id")
    logger.info(data[0]['RwdId'])
    logger.info(type(data[0]['RwdId']))
    # task.rwd_id = data[0]['RwdId']
    rwd_id = data[0]['RwdId']
    print "rwd_id: %s " % rwd_id
    # tasks = Task.objects.filter_active(id=task_id)
    # tasks.update(rwd_id=rwd_id)
    task.rwd_id = rwd_id
    task.save()
    logger.info(task.id)
    logger.info(task.rwd_id)
    res = begin_wb_info(link_account=link_account, link_token=link_token, task_sheet_id=data[0]['RwdId'])
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    logger.info(task.id)
    logger.info(u'最后了')
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=40)
    if not status:
        print task_id, msg, u'维保开始'
        # print task_id, msg
        return ErrorCode.TASK_BEGIN_REGISTER_FAIL

    return ErrorCode.SUCCESS


def end_task(link_account, link_token, task_id, sign_image, result, person):

    logger.info(u"结束任务。。。。。。")
    start_time = datetime.datetime.now()
    task = Task.objects.get(id=task_id)
    task_sheet_id = task.rwd_id
    operate_type = task.get_maintain_type_display()
    operate_type = operate_type[-2:]
    # card_id = []
    # workers = task.worker
    # workers = json.loads(workers)
    # persons = Person.objects.filter_active(id__in=workers)
    # for person in persons:
    #     if person.t1_card_no:
    #         card_id.append(person.t1_card_no)
    #     elif person.t2_card_no:
    #         card_id.append(person.t2_card_no)
    # card_id = ','.join(card_id)
    card_id = person.t1_card_no if person.t1_card_no else person.t2_card_no
    result = json.loads(result)
    report = result['maintenance_report']
    items = result['property_item']
    media_type = u'照片'
    pic = []
    extra = result['extra']
    for e in extra:
        material_name = e['note']
        material_url = e['image']
        part_name = e['materials']
        record = {
                'MaterialName': material_name,
                'MaterialUrl': material_url,
                'Partname': part_name,
                 }
        pic.append(record)
    lic = result['selects']
    sign_picture = sign_image

    logger.info(u"请求市局接口。。。。。。")
    res = end_wb_info(link_account, link_token, task_sheet_id, operate_type, card_id, sign_picture, report, items,
                      media_type, lic, pic)
    logger.info(u"市局接口接受完毕。。。。。。")
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    logger.info(u"创建记录。。。。。。")
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=50)
    if not status:
        logger.info(task_id)
        logger.info(u"完成维保确认 msg: ")
        logger.info(msg)
        task.status = 140
        task.save()
        if msg == u'更新失败，维保任务不存在或已提交' or msg == '更新失败，维保任务不存在或已提交':
            return ErrorCode.SUCCESS
        return ErrorCode.TASK_COMPLETE_REGISTER_FAIL
    return ErrorCode.SUCCESS


def estate_confirm_registry(link_account, link_token, task_id, signature, estate_confirm):

    start_time = datetime.datetime.now()
    task = Task.objects.get(id=task_id)
    task_sheet_id = task.rwd_id
    estate_sign_url = signature
    assessment = estate_confirm
    res = estate_confirm_info(link_account, link_token, task_sheet_id, estate_sign_url, assessment)
    status = res['Status']
    msg = res['Message']
    data = res['Data']
    reg_info = res['reg_info']
    ret_info = res['ret_info']
    end_time = datetime.datetime.now()
    Registry.objects.create(type_for_reg='Task', reg_obj_id=task_id, start_time=start_time,
                            end_time=end_time, status=status, msg=msg, data=data, reg_info=reg_info,
                            ret_info=ret_info, task_type=60)
    if not status:
        print task_id, msg, u'物业确认'
        task.status = 90
        task.save()
        return ErrorCode.ESTATE_CONFIRM_REGISTER_FAIL
    # test_for_celery.delay('Task', task_id)
    if settings.ANOTHER_REGISTRY:
        another_update_maintain_record.delay(task_id)
    return ErrorCode.SUCCESS


"""
向市局另一部门备案
"""


# 登录获取session号
def get_session():
    """
    id:由服务分配的平台ID
    ac:由服务分发的平台鉴权码
    ver:平台程序遵循的协议版本号
    t:发送时间戳
    :return:
    """
    data = {
        "login": {
            "id": "006",
            "ac": "HC",
            "ver": "4.0",
            "t": ""
        }
    }
    ts = time.time()
    T1 = time.localtime(ts)
    T2 = time.strftime('%Y%m%d%H%M%S', T1)
    data['login']['t'] = T2
    try:
        res = requests.post(settings.REGISTRY_INFO['INTERFACE']['LOGIN'], json=data)
    except Exception as e:
        ret_info = u"登录接口服务器通讯失败，POST请求异常"
        ret = {"Status": False, "Message": u"登录接口服务器通讯失败，POST请求异常", "Data": None,
               "reg_info": json.dumps(data), "ret_info": json.dumps(ret_info)}
        return ret
    if res.status_code == 200:
        res = res.json()
        if res['ret'].has_key('login'):
            ret = {
                "Status": False,
                "Message": res['ret']['login'][0]['d'],
                "Data": None
            }
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(res)})
        else:
            ret = {
                "Status": True,
                "Message": res['ret']['d'],
                "Data": None
            }
            ret.update({"reg_info": json.dumps(data), "ret_info": json.dumps(res), "session": res['ret']['ses']})
        return ret
    else:
        ret_info = u"登录接口服务器故障, HTTP Status Code: %s" % res.status_code
        ret = {"Status": False, "Message": u"登录接口服务器故障", "Data": None, "reg_info": json.dumps(data),
               "ret_info": json.dumps(ret_info)}
        return ret


# 维保单位信息变更或新增备案
def another_registry_company(code, name, per, enterpriseId, tel, addr, tm):
    """
    ses :平台在登录时从服务处获取的 ses值
    en  :企业enterprise缩写
    code :统一社会信用代码
    name : 企业名称
    per :企业法人
    enterpriseId: 惠城系统中单位的唯一识别码
    tel: 企业联系电话
    addr: 企业地址
    """
    ret_data = get_session()
    if ret_data['Status']:
        data = {
            'ses': ret_data['session'],
            'en': [
                {
                    'code': code,
                    'name': name,
                    'per': per,
                    'enterpriseId': enterpriseId,
                    'tel': tel,
                    'addr': addr,
                    'tm': tm
                }
            ]
        }
        try:
            res = requests.post(settings.REGISTRY_INFO['INTERFACE']['COMPANY'], json=data)
        except Exception as e:
            ret_info = u"备案接口服务器通讯失败，POST请求异常"
            ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
            return ret

        if res.status_code == 200:
            if res:
                ret = res.json()
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
            else:
                res = {
                    "Status": False,
                    "Message": u"备案服务器异常",
                    "Data": None
                }
                ret = res
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
        else:
            ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
            ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
        return ret
    else:
        return ret_data


def another_registry_person(id, enterpriseId, personId, name, phone, entcode, tm):
    """

    :param ses: 平台在登录时从服务处获取的 ses值
    :param id: 维保人员身份证号码
    :param enterpriseId: 维保人员所属企业ID在惠城的唯一识别号
    :param personId: 维保人员在惠城的唯一识别号
    :param name: 姓名
    :param sex: 性别
    :param phone: 手机号
    :param entcode: 所属企业信用代码
    :return:
    """
    ret_data = get_session()
    if ret_data['Status']:
        data = {
            'ses': ret_data['session'],
            'mp': [
                {
                    'id': id,
                    'enterpriseId': enterpriseId,
                    'personId': personId,
                    'name': name,
                    'sex': '',
                    'phone': phone,
                    'entcode': entcode,
                    'tm': tm
                }
            ]
        }

        try:
            res = requests.post(settings.REGISTRY_INFO['INTERFACE']['PERSON'], json=data)
        except Exception as e:
            ret_info = u"备案接口服务器通讯失败，POST请求异常"
            ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
            return ret

        if res.status_code == 200:
            if res:
                ret = res.json()
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
            else:
                res = {
                        "Status": False,
                        "Message": u"备案服务器异常",
                        "Data": None
                    }
                ret = res
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
        else:
            ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
            ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
        return ret
    else:
        return ret_data


# 维保记录信息变更或新增备案
def another_registry_mantainance(mno, e, name, maintenancePersonIds, enterpriseId, entname, mt, mtype,
                                 mresult, mconf, tm):
    """

    :param ses: 平台在登录时从服务处获取的 ses值
    :param mno: 维保工单号
    :param e: 电梯注册码
    :param name: 维保人员姓名
    :param maintenancePersonIds: 维保人员id
    :param enterpriseId: 维保单位id
    :param entname: 维保单位名称
    :param mt: 维保时间
    :param mtype: 维保类别
    :param mresult: 维保结论
    :param mconf: 维保确认人
    :return:
    """
    ret_data = get_session()
    if ret_data['Status']:
        data = {
            'ses': ret_data['session'],
            'mr': [
                {
                    'mno': mno,
                    'e': e,
                    'name': name,
                    'maintenancePersonIds': maintenancePersonIds,
                    'enterpriseId': enterpriseId,
                    'entname': entname,
                    'mt': mt,
                    'mtype': mtype,
                    'mresult': mresult,
                    'mconf': mconf,
                    'tm': tm
                }
            ]
        }

        try:
            res = requests.post(settings.REGISTRY_INFO['INTERFACE']['MAINTAIN'], json=data)
        except Exception as e:
            ret_info = u"备案接口服务器通讯失败，POST请求异常"
            ret = {"Status": False, "Message": "备案接口服务器通讯失败", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
            return ret

        if res.status_code == 200:
            if res:
                ret = res.json()
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
            else:
                res = {
                        "Status": False,
                        "Message": u"备案服务器异常",
                        "Data": None
                    }
                ret = res
                ret.update({"reg_info": json.dumps(data, ensure_ascii=False), "ret_info": json.dumps(ret, ensure_ascii=False)})
        else:
            ret_info = u"备案服务器故障, HTTP Status Code: %s" % res.status_code
            ret = {"Status": False, "Message": "备案接口服务器故障", "Data": None, "reg_info": json.dumps(data, ensure_ascii=False),
                   "ret_info": json.dumps(ret_info, ensure_ascii=False)}
        return ret
    else:
        return ret_data


def another_update_company(type_for_reg, reg_obj_id):
    logger.info(u'维保单位信息变更或新增备案开始-another')
    print u"维保公司备案2开始"
    maintain_company_obj = type_for_reg.objects.get(id=reg_obj_id)
    code = maintain_company_obj.unified_code
    name = maintain_company_obj.name
    per = maintain_company_obj.legal_person
    enterprise_id = str(maintain_company_obj.id)
    tel = maintain_company_obj.company_telephone
    addr = maintain_company_obj.register_address

    ts = time.time()
    T1 = time.localtime(ts)
    tm = time.strftime('%Y%m%d%H%M%S', T1)

    res = another_registry_company(code, name, per, enterprise_id, tel, addr, tm)
    print res
    print u"维保公司备案2完毕"
    logger.info(u'维保单位信息变更或新增备案完毕-another')


def another_update_person(type_for_reg, reg_obj_id):
    print u"维保人员备案2开始"
    logger.info(u'维保人员信息变更或新增备案开始-another')
    person_obj = type_for_reg.objects.get(id=reg_obj_id)
    id = person_obj.card_id
    enterprise_id = str(person_obj.company.id)
    person_id = str(person_obj.id)
    name = person_obj.auth_user.real_name
    phone = person_obj.auth_user.phone
    entcode = person_obj.company.unified_code

    ts = time.time()
    T1 = time.localtime(ts)
    tm = time.strftime('%Y%m%d%H%M%S', T1)
    res = another_registry_person(id, enterprise_id, person_id, name, phone, entcode, tm)
    print res
    print u"维保人员备案2完毕"
    logger.info(u'维保人员信息变更或新增备案完毕-another')


@shared_task
def another_update_maintain_record(reg_obj_id):
    print u"维保结果备案2开始"
    logger.info(u'维保记录信息变更或新增备案开始-another')
    task_obj = Task.objects.get(id=reg_obj_id)
    mno = task_obj.sn
    e = task_obj.elevator.register_code
    name = task_obj.maintainer_name
    maintenance_person_id = str(task_obj.maintainer_id)

    enterprise_id = task_obj.elevator.maintain_company.id
    entname = Person.objects.get(id=task_obj.maintainer_id).company.name
    mt = task_obj.day.strftime("%Y%m%d")

    maintain_type = task_obj.maintain_type
    if maintain_type in [110, 150, 190, 230]:
        mtype = "1"
    elif maintain_type in [100, 140, 180, 220]:
        mtype = "3"
    elif maintain_type in [120, 160, 200, 240]:
        mtype = "4"
    elif maintain_type in [90, 130, 170, 210]:
        mtype = "5"

    result = json.loads(task_obj.result)
    items = result["selects"]
    commit = True
    for item in items:
        if item['ckvalue'] is "需修理":
            mresult = "2"
            commit = False
            break
        else:
            continue
    if commit:
        mresult = "1"

    mconf = task_obj.elevator.property_company.name

    ts = time.time()
    T1 = time.localtime(ts)
    tm = time.strftime('%Y%m%d%H%M%S', T1)

    res = another_registry_mantainance(mno, e, name, maintenance_person_id, enterprise_id, entname, mt, mtype,
                                       mresult, mconf, tm)
    print res
    print u"维保结果备案2完毕"
    logger.info(u'维保记录信息变更或新增备案完毕-another')

































